using Masuit.Tools;
using Masuit.Tools.Reflection;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NPinyin;
using Simple.Common.Helpers;
using Simple.Contracts.Contracts;
using Simple.Contracts.Enums.Common;
using Simple.Contracts.Enums.Elderly;
using Simple.Contracts.Models;
using Simple.Contracts.Models.Common;
using Simple.Contracts.Models.Common.File;
using Simple.Contracts.Models.Common.Page;
using Simple.Repository;
using Simple.Repository.SimpleEntitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static FreeSql.Internal.GlobalFilter;

namespace Simple.Services.Services
{
    /// <summary>
    /// 老人信息-服务类
    /// </summary>
    public class ElderlyService : BaseService, IElderlyService
    {
        private readonly IConfiguration _configuration;
        public ElderlyService(FreeSqlCloud freeSqlCloud, IConfiguration configuration, CurrentAccount currentAccount) : base(freeSqlCloud, currentAccount)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 获取老人列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<PageDto<ElderlyInfoDto>>> List(ElderlyInfoListInput input)
        {
            var elderlyInfoList = await _simpleFreeSql.Select<Elderly>()
                .Where(x => x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
                .WhereIf(!string.IsNullOrEmpty(input.name), x => x.Name.Contains(input.name!) || x.NamePinyinCapitalLetter.Contains(input.name!))
                .WhereIf(!string.IsNullOrEmpty(input.nickName), x => x.NickName.Contains(input.nickName!) || x.NickNamePinyinCapitalLetter.Contains(input.nickName!))
                .WhereIf(!string.IsNullOrEmpty(input.idCard), x => x.IdCard.Contains(input.idCard!))
                .WhereIf(!string.IsNullOrEmpty(input.roomNumber), x => x.RoomNumber.Contains(input.roomNumber!))
                .WhereIf(input.status.HasValue, x => x.Status == input.status!.Value)
                .WhereIf(input.gender.HasValue, x => x.Gender == input.gender!.Value)
                .WhereIf(input.bloodType.HasValue, x => x.BloodType == input.bloodType!.Value)
                .WhereIf(input.mobilityStatus.HasValue, x => x.MobilityStatus == input.mobilityStatus!.Value)
                .WhereIf(input.IsSettingCarePlan.HasValue, x => x.IsSettingCarePlan == input.IsSettingCarePlan!.Value)
                .Count(out var total)
                .Page(input.pageNum, input.pageSize)
                .OrderByDescending(x => x.CreateTime)
                .ToListAsync();

            var list = new List<ElderlyInfoDto>();
            var elderlyCareWorkerList = await _simpleFreeSql.Select<ElderlyCareWorker>().Where(x => x.CompanyId == _currentAccount.CompanyId).ToListAsync();
            foreach (var elderly in elderlyInfoList)
            {
                list.Add(new ElderlyInfoDto()
                {
                    Id = elderly.Id,
                    Name = elderly.Name,
                    Gender = elderly.Gender,
                    IdCard = elderly.IdCard,
                    DateOfBirth = elderly.DateOfBirth?.ToString("yyyy-MM-dd"),
                    Age = elderly.DateOfBirth.HasValue ? TimeHelper.GetAge(elderly.DateOfBirth!.Value) : null,
                    RoomNumber = elderly.RoomNumber,
                    BedNumber = elderly.BedNumber,
                    ContactPhone = elderly.ContactPhone,
                    EmergencyContactName = elderly.EmergencyContactName,
                    EmergencyContactRelation = elderly.EmergencyContactRelation,
                    EmergencyContactPhone = elderly.EmergencyContactPhone,
                    Allergies = elderly.Allergies,
                    BloodType = elderly.BloodType,
                    MobilityStatus = elderly.MobilityStatus,
                    CheckInDate = elderly.CheckInDate.HasValue ? elderly.CheckInDate.Value.ToString("yyyy-MM-dd") : null,
                    Status = elderly.Status,
                    AvatarUrl = elderly.AvatarUrl,
                    PhotoUrls = !string.IsNullOrEmpty(elderly.PhotoUrls) ? JsonConvert.DeserializeObject<List<ImageModel>>(elderly.PhotoUrls) : new List<ImageModel>(),
                    WechatId = elderly.WechatId,
                    CreateTime = elderly.CreateTime.ToString("yyyy-MM-dd"),
                    MajorMedicalHistory = elderly.MajorMedicalHistory,
                    CurrentMedications = elderly.CurrentMedications,
                    DietaryRequirements = elderly.DietaryRequirements,
                    ContractExpiryDate = elderly.ContractExpiryDate.HasValue ? elderly.ContractExpiryDate.Value!.ToString("yyyy-MM-dd") : null,
                    PersonalHabits = elderly.PersonalHabits,
                    Notes = elderly.Notes,
                    Address = elderly.Address,
                    ChineseZodiac = elderly.ChineseZodiac,
                    NickName = elderly.NickName,
                    IsSettingCarePlan = elderly.IsSettingCarePlan,
                    PersonalizedCareNeeds = elderly.PersonalizedCareNeeds,
                    RiskPrevention = elderly.RiskPrevention,
                    SpecialCarePrecautions = elderly.SpecialCarePrecautions,
                    ElderlyCareWorkerList = elderlyCareWorkerList.Where(x => x.ElderlyId == elderly.Id).Select(x => new ElderlyCareWorkerDto() { EmployeeId = x.EmployeeId, EmployeeName = x.EmployeeName }).ToList()
                });
            }
            return Result<ElderlyInfoDto>.PageSuccess(list, total, input);
        }

        /// <summary>
        /// 保存老人信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<long>> Save(ElderlyInfoSaveInput input)
        {
            // 验证身份证号码
            if (!input.IdCard.IsNullOrEmpty())
            {
                if (!IdNumberHelper.CheckIdNumberFormat(input.IdCard))
                {
                    return Result<long>.FriendlyReminder("身份证号码格式不正确");
                }

                // 验证身份证
                if (input.Id.HasValue)
                {
                    // 检查身份证号是否已存在（排除当前编辑的老人）
                    var exists = await _simpleFreeSql.Select<Elderly>()
                        .Where(x => x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0 && x.IdCard == input.IdCard)
                        .WhereIf(input.Id.HasValue, x => x.Id != input.Id.Value)
                        .AnyAsync();
                    if (exists)
                    {
                        return Result<long>.FriendlyReminder("该身份证号的老人信息已存在");
                    }
                }

                input.Gender = IdNumberHelper.GetIdNumberGender(input.IdCard);
                input.DateOfBirth = IdNumberHelper.GetIdNumberBirthday(input.IdCard);
                input.ChineseZodiac = IdNumberHelper.GetChineseZodiac(input.IdCard);
            }

            // 保存老人信息
            long elderlyId = 0;
            var elderly = new Elderly()
            {
                CompanyId = _currentAccount.CompanyId,
                Name = input.Name,
                NamePinyinCapitalLetter = input.Name.IsNullOrEmpty() ? null : Pinyin.GetInitials(input.Name),
                NickName = input.NickName,
                NickNamePinyinCapitalLetter = input.NickName.IsNullOrEmpty() ? null : Pinyin.GetInitials(input.NickName),
                Gender = input.Gender,
                DateOfBirth = input.DateOfBirth,
                ChineseZodiac = input.ChineseZodiac,
                IdCard = input.IdCard,
                RoomNumber = input.RoomNumber,
                BedNumber = input.BedNumber,
                ContactPhone = input.ContactPhone,
                WechatId = input.WechatId,
                EmergencyContactName = input.EmergencyContactName,
                EmergencyContactRelation = input.EmergencyContactRelation,
                EmergencyContactPhone = input.EmergencyContactPhone,
                BloodType = input.BloodType.HasValue ? input.BloodType!.Value : (int)BloodTypeEnum.未知,
                Allergies = input.Allergies,
                MajorMedicalHistory = input.MajorMedicalHistory,
                CurrentMedications = input.CurrentMedications,
                MobilityStatus = input.MobilityStatus,
                DietaryRequirements = input.DietaryRequirements,
                CheckInDate = input.CheckInDate,
                ContractExpiryDate = input.ContractExpiryDate,
                PhotoUrls = input.PhotoUrls == null ? "[]" : JsonConvert.SerializeObject(input.PhotoUrls),
                PersonalHabits = input.PersonalHabits,
                Address = input.Address,
                Notes = input.Notes,
                AvatarUrl = input.AvatarUrl,
                IsDelete = 0,
                CreateBy = _currentAccount.EmployeeId,
                CreateTime = DateTime.Now,
                UpdateBy = _currentAccount.EmployeeId,
                UpdateTime = DateTime.Now,
                Status = input.Status,
                IsSettingCarePlan = 0
            };

            if (input.Id.HasValue)
            {
                var oldElderly = await _simpleFreeSql.Select<Elderly>().Where(x => x.Id == input.Id.Value && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0).FirstAsync();
                if (oldElderly == null)
                {
                    return Result<long>.FriendlyReminder("该老人信息不存在或已被删除");
                }
                elderly.Id = oldElderly.Id;
                elderly.CreateTime = oldElderly.CreateTime;
                elderly.CreateBy = oldElderly.CreateBy;
                elderly.UpdateTime = DateTime.Now;
                elderly.UpdateBy = _currentAccount.EmployeeId;

                elderly.IsSettingCarePlan = oldElderly.IsSettingCarePlan;
                elderly.PersonalizedCareNeeds = oldElderly.PersonalizedCareNeeds;
                elderly.RiskPrevention = oldElderly.RiskPrevention;
                elderly.SpecialCarePrecautions = oldElderly.SpecialCarePrecautions;

                await _simpleFreeSql.Update<Elderly>().SetSource(elderly).ExecuteAffrowsAsync();
                elderlyId = elderly.Id;

                await _simpleFreeSql.Delete<ElderlyCareWorker>().Where(x => x.CompanyId == _currentAccount.CompanyId && x.ElderlyId == elderlyId).ExecuteAffrowsAsync();
            }
            else
            {
                elderly.Status = (int)ElderlyStatusEnum.在住;
                elderlyId = await _simpleFreeSql.Insert<Elderly>(elderly).ExecuteIdentityAsync();
            }

            if (input.ElderlyCareWorkerList != null && input.ElderlyCareWorkerList.Any())
            {
                var elderlyCareWorkerEnttiys = input.ElderlyCareWorkerList.Select(x => new ElderlyCareWorker()
                {
                    CompanyId = _currentAccount.CompanyId,
                    ElderlyId = elderlyId,
                    EmployeeId = x.EmployeeId,
                    EmployeeName = x.EmployeeName
                }).ToList();
                await _simpleFreeSql.Insert<ElderlyCareWorker>(elderlyCareWorkerEnttiys).ExecuteAffrowsAsync();
            }

            return Result<long>.Success(elderlyId);
        }

        /// <summary>
        /// 删除老人信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<bool>> Delete(ElderlyInfoDeleteInput input)
        {
            await _simpleFreeSql.Update<Elderly>()
                .Set(x => x.IsDelete, 1)
                .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                .Set(x => x.UpdateTime, DateTime.Now)
                .Where(x => x.CompanyId == _currentAccount.CompanyId && input.id.Contains(x.Id))
                .ExecuteAffrowsAsync();
            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 设置老人状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<bool>> SetStatus(ElderlyInfoSetStatusInput input)
        {
            var elderly = await _simpleFreeSql.Select<Elderly>().Where(x => x.Id == input.id && x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0).FirstAsync();
            if (elderly == null)
            {
                return Result<bool>.FriendlyReminder("该老人信息不存在或已被删除");
            }

            elderly.Status = input.Status;
            elderly.UpdateBy = _currentAccount.EmployeeId;
            elderly.UpdateTime = DateTime.Now;

            await _simpleFreeSql.Update<Elderly>().SetSource(elderly).ExecuteAffrowsAsync();
            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 保存老人照护记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<bool>> SaveElderlyCarePlan(SaveElderlyCarePlanInput input)
        {
            var isSettingCarePlan = 0;
            if(input.PlanMissionList != null&& input.PlanMissionList.Where(x => x.IsDelete == 0).Any())
            {
                isSettingCarePlan = 1;
            }
            // 更新老人照护信息
            await _simpleFreeSql.Update<Elderly>()
                 .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                 .Set(x => x.UpdateTime, DateTime.Now)
                 .Set(x => x.MajorMedicalHistory, input.MajorMedicalHistory)
                 .Set(x => x.Allergies, input.Allergies)
                 .Set(x => x.RiskPrevention, input.RiskPrevention)
                 .Set(x => x.SpecialCarePrecautions, input.SpecialCarePrecautions)
                 .Set(x => x.PersonalizedCareNeeds, input.PersonalizedCareNeeds)
                 .Set(x => x.IsSettingCarePlan, isSettingCarePlan)
                 .Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == input.ElderlyId)
                 .ExecuteAffrowsAsync();

            // 更新来人照护计划动作列表
            if (input.PlanMissionList != null)
            {
                foreach (var item in input.PlanMissionList)
                {
                    var entity = await _simpleFreeSql.Select<ElderlyCareMission>()
                       .Where(x => x.Id == item.Id && x.CompanyId == _currentAccount.CompanyId && x.ElderlyId == input.ElderlyId)
                       .FirstAsync();
                    if (entity == null)
                    {
                        if (item.IsDelete == 1)
                        {
                            continue;
                        }
                        entity = new ElderlyCareMission()
                        {
                            ElderlyId = input.ElderlyId,
                            Name = item.Name,
                            Description = item.Description,
                            CategorizeId = item.CategorizeId,
                            CareMissionId = item.CareMissionId,
                            CreateBy = _currentAccount.EmployeeId,
                            CompanyId = _currentAccount.CompanyId,
                            CreateTime = DateTime.Now,
                            DailyMissionEndTime = item.DailyMissionEndTime,
                            DailyMissionEndTimeValue = item.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionEndTime!.Replace(":", "")),
                            DailyMissionExecutionCount = item.DailyMissionExecutionCount,
                            DailyMissionStartTime = item.DailyMissionStartTime,
                            DailyMissionStartTimeValue = item.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionStartTime!.Replace(":", "")),
                            IsDailyMission = item.IsDailyMission,
                            IsDelete = 0,
                            Sort = item.Sort,
                            UpdateBy = _currentAccount.EmployeeId,
                            UpdateTime = DateTime.Now,
                            IsTakePhotos = item.IsTakePhotos.HasValue && item.IsTakePhotos!.Value ? 1 : 0,
                            CareWorkerEmployeeIds = item.CareWorkerEmployeeIds
                        };
                        await _simpleFreeSql.Insert<ElderlyCareMission>(entity).ExecuteAffrowsAsync();
                    }
                    else
                    {
                        entity.Name = item.Name;
                        entity.Description = item.Description;
                        entity.IsDailyMission = item.IsDailyMission;
                        entity.DailyMissionStartTime = item.DailyMissionStartTime;
                        entity.DailyMissionStartTimeValue = item.DailyMissionStartTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionStartTime!.Replace(":", ""));
                        entity.DailyMissionEndTime = item.DailyMissionEndTime;
                        entity.DailyMissionEndTimeValue = item.DailyMissionEndTime.IsNullOrEmpty() ? null : int.Parse(item.DailyMissionEndTime!.Replace(":", ""));
                        entity.UpdateBy = _currentAccount.EmployeeId;
                        entity.UpdateTime = DateTime.Now;
                        entity.IsTakePhotos = item.IsTakePhotos.HasValue && item.IsTakePhotos!.Value ? 1 : 0;
                        entity.DailyMissionExecutionCount = item.DailyMissionExecutionCount;
                        entity.Sort = item.Sort;
                        entity.IsDelete = item.IsDelete;
                        entity.CareWorkerEmployeeIds = item.CareWorkerEmployeeIds;
                        await _simpleFreeSql.Update<ElderlyCareMission>().SetSource(entity).ExecuteAffrowsAsync();
                    }
                }
            }

            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 获取老人照护记录
        /// </summary>
        /// <param name="elderlyId"></param>
        /// <returns></returns>
        public async Task<Result<List<ElderlyCarePlanMissionDto>>> GetElderlyCarePlanMissionList(long elderlyId)
        {
            var list = await _simpleFreeSql.Select<ElderlyCareMission>()
                    .Where(x => x.CompanyId == _currentAccount.CompanyId && x.ElderlyId == elderlyId && x.IsDelete == 0)
                    .OrderByDescending(x => x.IsDailyMission)
                    .OrderBy(x => x.DailyMissionStartTimeValue)
                    .ToListAsync(x => new ElderlyCarePlanMissionDto()
                    {
                        CareMissionId = x.CareMissionId,
                        DailyMissionStartTime = x.DailyMissionStartTime,
                        IsDailyMission = x.IsDailyMission,
                        CategorizeId = x.CategorizeId,
                        DailyMissionEndTime = x.DailyMissionEndTime,
                        DailyMissionExecutionCount = x.DailyMissionExecutionCount,
                        IsDelete = x.IsDelete,
                        Description = x.Description,
                        Id = x.Id,
                        Name = x.Name,
                        Sort = x.Sort,
                        DailyMissionEndTimeValue = x.DailyMissionEndTimeValue,
                        DailyMissionStartTimeValue = x.DailyMissionStartTimeValue,
                        IsTakePhotos = x.IsTakePhotos == 1,
                        CareWorkerEmployeeIds = x.CareWorkerEmployeeIds
                    });
            return Result<List<ElderlyCarePlanMissionDto>>.Success(list);
        }

        /// <summary>
        /// 获取员工照护的老人列表
        /// </summary>
        /// <param name="EmployeeId"></param>
        /// <returns></returns>
        public async Task<Result<List<ElderlyCareInfoDto>>> GetElderlyByEmployeeId(long EmployeeId)
        {
            var completionStartTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            var completionEndTime = completionStartTime.AddDays(1);

            var elderlyInfoList = new List<ElderlyCareInfoDto>();
            var elderlyCareMissions = await _simpleFreeSql.Select<ElderlyCareMission>()
                .Where(x => x.CompanyId == _currentAccount.CompanyId && ("," + x.CareWorkerEmployeeIds + ",").Contains("," + EmployeeId + ","))
                .OrderByDescending(x => x.IsDailyMission)
                .OrderBy(x => x.DailyMissionStartTimeValue)
                .ToListAsync();
            if (elderlyCareMissions.Any())
            {
                var elderlyIds = elderlyCareMissions.Select(x => x.ElderlyId).Distinct().ToList();
                var elderlyList = await _simpleFreeSql.Select<Elderly>()
                    .Where(x => x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0 && elderlyIds.Contains(x.Id) && x.Status == 1)
                    .ToListAsync();
                foreach (var elderly in elderlyList)
                {
                    // 获取老人今天的照护记录
                    var elderlyCareRecordList = await _simpleFreeSql.Select<ElderlyCareRecord>().Where(x => x.ElderlyId == elderly.Id && x.IsDelete == 0 && completionStartTime <= x.CompletionTime && x.CompletionTime < completionEndTime).ToListAsync();

                    // 老人照护项目列表
                    var carePlanMissionList = new List<ElderlyCarePlanMissionInfoDto>();
                    var missionList = elderlyCareMissions.Where(x => x.ElderlyId == elderly.Id).ToList();
                    var completeMissionCount = 0;
                    foreach (var mission in missionList)
                    {
                        var executionCount = elderlyCareRecordList.Where(x => x.ElderlyCareMissionId == mission.Id).Count();
                        var isComplete = (mission.DailyMissionExecutionCount ?? 1) <= executionCount;
                        carePlanMissionList.Add(new ElderlyCarePlanMissionInfoDto()
                        {
                            CareMissionId = mission.CareMissionId,
                            DailyMissionStartTime = mission.DailyMissionStartTime,
                            IsDailyMission = mission.IsDailyMission,
                            CategorizeId = mission.CategorizeId,
                            DailyMissionEndTime = mission.DailyMissionEndTime,
                            DailyMissionExecutionCount = mission.DailyMissionExecutionCount,
                            IsDelete = mission.IsDelete,
                            Description = mission.Description,
                            Id = mission.Id,
                            Name = mission.Name,
                            Sort = mission.Sort,
                            DailyMissionEndTimeValue = mission.DailyMissionEndTimeValue,
                            DailyMissionStartTimeValue = mission.DailyMissionStartTimeValue,
                            IsTakePhotos = mission.IsTakePhotos == 1,
                            CareWorkerEmployeeIds = mission.CareWorkerEmployeeIds,
                            ExecutionCount = executionCount,
                            IsComplete = isComplete
                        });
                        if (isComplete)
                        {
                            completeMissionCount++;
                        }
                    }
                    elderlyInfoList.Add(new ElderlyCareInfoDto()
                    {
                        Id = elderly.Id,
                        Name = elderly.Name,
                        Gender = elderly.Gender,
                        IdCard = elderly.IdCard,
                        DateOfBirth = elderly.DateOfBirth?.ToString("yyyy-MM-dd"),
                        Age = elderly.DateOfBirth.HasValue ? TimeHelper.GetAge(elderly.DateOfBirth!.Value) : null,
                        RoomNumber = elderly.RoomNumber,
                        BedNumber = elderly.BedNumber,
                        ContactPhone = elderly.ContactPhone,
                        EmergencyContactName = elderly.EmergencyContactName,
                        EmergencyContactRelation = elderly.EmergencyContactRelation,
                        EmergencyContactPhone = elderly.EmergencyContactPhone,
                        Allergies = elderly.Allergies,
                        BloodType = elderly.BloodType,
                        MobilityStatus = elderly.MobilityStatus,
                        CheckInDate = elderly.CheckInDate.HasValue ? elderly.CheckInDate.Value.ToString("yyyy-MM-dd") : null,
                        Status = elderly.Status,
                        AvatarUrl = elderly.AvatarUrl,
                        PhotoUrls = !string.IsNullOrEmpty(elderly.PhotoUrls) ? JsonConvert.DeserializeObject<List<ImageModel>>(elderly.PhotoUrls) : new List<ImageModel>(),
                        WechatId = elderly.WechatId,
                        CreateTime = elderly.CreateTime.ToString("yyyy-MM-dd"),
                        MajorMedicalHistory = elderly.MajorMedicalHistory,
                        CurrentMedications = elderly.CurrentMedications,
                        DietaryRequirements = elderly.DietaryRequirements,
                        ContractExpiryDate = elderly.ContractExpiryDate.HasValue ? elderly.ContractExpiryDate.Value!.ToString("yyyy-MM-dd") : null,
                        PersonalHabits = elderly.PersonalHabits,
                        Notes = elderly.Notes,
                        Address = elderly.Address,
                        ChineseZodiac = elderly.ChineseZodiac,
                        NickName = elderly.NickName,
                        IsSettingCarePlan = elderly.IsSettingCarePlan,
                        PersonalizedCareNeeds = elderly.PersonalizedCareNeeds,
                        RiskPrevention = elderly.RiskPrevention,
                        SpecialCarePrecautions = elderly.SpecialCarePrecautions,
                        ElderlyCareWorkerList = new List<ElderlyCareWorkerDto>(),
                        CarePlanMissionList = carePlanMissionList,
                        CompleteMissionCount= completeMissionCount
                    });
                }
            }

            return Result<List<ElderlyCareInfoDto>>.Success(elderlyInfoList);
        }

        /// <summary>
        /// 获取老人照护任务详情
        /// </summary>
        /// <param name="elderlyCarePlanMissionId"></param>
        /// <returns></returns>
        public async Task<Result<ElderlyCarePlanMissionDto?>> GetElderlyCarePlanMission(long elderlyCarePlanMissionId)
        {
            var mission = await _simpleFreeSql.Select<ElderlyCareMission>()
                .Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == elderlyCarePlanMissionId)
                .FirstAsync();
            if (mission == null)
            {
                return Result<ElderlyCarePlanMissionDto?>.Success(null);
            }

            var res = new ElderlyCarePlanMissionInfoDto()
            {
                CareMissionId = mission.CareMissionId,
                DailyMissionStartTime = mission.DailyMissionStartTime,
                IsDailyMission = mission.IsDailyMission,
                CategorizeId = mission.CategorizeId,
                DailyMissionEndTime = mission.DailyMissionEndTime,
                DailyMissionExecutionCount = mission.DailyMissionExecutionCount,
                IsDelete = mission.IsDelete,
                Description = mission.Description,
                Id = mission.Id,
                Name = mission.Name,
                Sort = mission.Sort,
                DailyMissionEndTimeValue = mission.DailyMissionEndTimeValue,
                DailyMissionStartTimeValue = mission.DailyMissionStartTimeValue,
                IsTakePhotos = mission.IsTakePhotos == 1,
                CareWorkerEmployeeIds = mission.CareWorkerEmployeeIds,
                ExecutionCount = 0,
                IsComplete = false
            };
            return Result<ElderlyCarePlanMissionDto?>.Success(res);
        }

        /// <summary>
        /// 保存老人照护记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<bool>> SaveElderlyCareRecord(SaveElderlyCareRecordInput input)
        {
            var elderlyCareMission = await _simpleFreeSql.Select<ElderlyCareMission>().Where(x => x.CompanyId == _currentAccount.CompanyId && x.Id == input.careMissionId).FirstAsync();
            if (elderlyCareMission == null)
            {
                return Result<bool>.Success(false);
            }

            bool completionAtSpecifiedTime = true;
            if (!elderlyCareMission.DailyMissionStartTime.IsNullOrEmpty() && !elderlyCareMission.DailyMissionEndTime.IsNullOrEmpty())
            {
                var dailyMissionStartTime = DateTime.Parse($"{DateTime.Now.ToString("yyyy-MM-dd")} {elderlyCareMission.DailyMissionStartTime}:00");
                var dailyMissionEndTime = DateTime.Parse($"{DateTime.Now.ToString("yyyy-MM-dd")} {elderlyCareMission.DailyMissionEndTime}:59");
                completionAtSpecifiedTime = dailyMissionStartTime <= DateTime.Now && DateTime.Now <= dailyMissionEndTime;
            }

            // 添加照护记录
            var elderlyCareRecordEntity = new ElderlyCareRecord()
            {
                CompanyId = elderlyCareMission.CompanyId,
                ElderlyId = elderlyCareMission.ElderlyId,
                CategorizeId = elderlyCareMission.CategorizeId,
                CareMissionId = elderlyCareMission.CareMissionId,
                Name = elderlyCareMission.Name,
                Description = elderlyCareMission.Description,
                IsDailyMission = elderlyCareMission.IsDailyMission,
                DailyMissionStartTime = elderlyCareMission.DailyMissionStartTime,
                DailyMissionEndTime = elderlyCareMission.DailyMissionEndTime,
                DailyMissionStartTimeValue = elderlyCareMission.DailyMissionStartTimeValue,
                DailyMissionEndTimeValue = elderlyCareMission.DailyMissionEndTimeValue,
                DailyMissionExecutionCount = elderlyCareMission.DailyMissionExecutionCount,
                IsTakePhotos = elderlyCareMission.IsTakePhotos,
                CreateTime = DateTime.Now,
                CreateBy = _currentAccount.EmployeeId,
                UpdateTime = DateTime.Now,
                UpdateBy = _currentAccount.EmployeeId,
                Sort = elderlyCareMission.Sort,
                CareWorkerEmployeeIds = elderlyCareMission.CareWorkerEmployeeIds,
                IsDelete = 0,

                ElderlyCareMissionId = elderlyCareMission.Id,
                CompletionTime = DateTime.Now,
                CompletionAtSpecifiedTime = completionAtSpecifiedTime ? 1 : 0,
                CompletionBy = _currentAccount.EmployeeId,
                RecordContent = input.recordContent,
            };
            var elderlyCareRecordId = await _simpleFreeSql.Insert<ElderlyCareRecord>(elderlyCareRecordEntity).ExecuteIdentityAsync();

            // 添加照护记录图片
            var elderlyCareRecordMediaList = new List<ElderlyCareRecordMedia>();
            if (input.recordMp3FileList != null && input.recordMp3FileList.Any())
            {
                foreach (var item in input.recordMp3FileList)
                {
                    elderlyCareRecordMediaList.Add(new ElderlyCareRecordMedia()
                    {
                        FileId = item.fileId,
                        FileUrl = item.fileUrl,
                        FileType = "mp3",
                        Mp3Second = item.durationSecond,
                        Mp3Text = null,
                        CreateBy = _currentAccount.EmployeeId,
                        CreateTime = DateTime.Now,
                        IsDelete = 0,
                        UpdateBy = _currentAccount.EmployeeId,
                        UpdateTime = DateTime.Now,
                        CompanyId = _currentAccount.CompanyId,
                        ElderlyCareRecordId = elderlyCareRecordId,
                    });
                }
            }
            if (input.recordImageFileList != null && input.recordImageFileList.Any())
            {
                foreach (var item in input.recordImageFileList)
                {
                    elderlyCareRecordMediaList.Add(new ElderlyCareRecordMedia()
                    {
                        FileId = item.fileId,
                        FileUrl = item.fileUrl,
                        FileType = "image",
                        CreateBy = _currentAccount.EmployeeId,
                        CreateTime = DateTime.Now,
                        IsDelete = 0,
                        UpdateBy = _currentAccount.EmployeeId,
                        UpdateTime = DateTime.Now,
                        CompanyId = _currentAccount.CompanyId,
                        ElderlyCareRecordId = elderlyCareRecordId,
                    });
                }
            }
            if (elderlyCareRecordMediaList.Any())
            {
                await _simpleFreeSql.Insert<ElderlyCareRecordMedia>(elderlyCareRecordMediaList).ExecuteAffrowsAsync();
            }
            await _simpleFreeSql.Update<ElderlyCareRecord>()
                .Set(x => x.ElderlyCareRecordMediaJson, JsonConvert.SerializeObject(elderlyCareRecordMediaList))
                .Where(x => x.Id == elderlyCareRecordId && x.CompanyId == _currentAccount.CompanyId)
                .ExecuteAffrowsAsync();

            // 删除上传的照护记录图片或视频
            var fileIds = new List<long>();
            if (input.recordImageDeleteFileList != null && input.recordImageDeleteFileList.Any())
            {
                var ids = input.recordImageDeleteFileList.Select(x => x.fileId).ToList();
                fileIds.AddRange(ids);
            }
            if (input.recordMp3DeleteFileList != null && input.recordMp3DeleteFileList.Any())
            {
                var ids = input.recordMp3DeleteFileList.Select(x => x.fileId).ToList();
                fileIds.AddRange(ids);
            }
            if (fileIds.Any())
            {
                await _simpleFreeSql.Update<CompanyFile>()
                    .Set(x => x.IsDelete, 1)
                    .Set(x => x.UpdateBy, _currentAccount.EmployeeId)
                    .Set(x => x.UpdateTime, DateTime.Now)
                    .Where(x => x.CompanyId == _currentAccount.CompanyId && fileIds.Contains(x.Id))
                    .ExecuteAffrowsAsync();
            }

            return Result<bool>.Success(true);
        }

        /// <summary>
        /// 获取老人照护记录列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Result<PageDto<ElderlyCareRecordDto>>> GetElderlyCareRecordList(GetElderlyCareRecordListInput input)
        {
            var elderlyCareRecordList = await _simpleFreeSql.Select<ElderlyCareRecord>()
               .Where(x => x.CompanyId == _currentAccount.CompanyId && x.IsDelete == 0)
               .WhereIf(input.ElderlyId.HasValue, x => x.ElderlyId == input.ElderlyId!.Value)
               .Count(out var total)
               .Page(input.pageNum, input.pageSize)
               .OrderByDescending(x => x.CreateTime)
               .ToListAsync();

            var employeeDic = await _simpleFreeSql.Select<Employee>().Where(x => x.CompanyId == _currentAccount.CompanyId).ToDictionaryAsync(x => x.Id);
            var list = new List<ElderlyCareRecordDto>();
            foreach (var r in elderlyCareRecordList)
            {
                var line = new ElderlyCareRecordDto()
                {
                    Id = r.Id,
                    ElderlyId = r.ElderlyId,
                    CategorizeId = r.CategorizeId,
                    CareMissionId = r.CareMissionId,
                    Name = r.Name,
                    Description = r.Description,
                    IsDailyMission = r.IsDailyMission,
                    DailyMissionStartTime = r.DailyMissionStartTime,
                    DailyMissionEndTime = r.DailyMissionEndTime,
                    DailyMissionEndTimeValue = r.DailyMissionEndTimeValue,
                    DailyMissionStartTimeValue = r.DailyMissionStartTimeValue,
                    DailyMissionExecutionCount = r.DailyMissionExecutionCount,
                    IsTakePhotos = r.IsTakePhotos,
                    CreateTime = r.CreateTime,
                    CreateBy = r.CreateBy,
                    UpdateTime = r.UpdateTime,
                    UpdateBy = r.UpdateBy,
                    Sort = r.Sort,
                    CareWorkerEmployeeIds = r.CareWorkerEmployeeIds,
                    IsDelete = r.IsDelete,
                    ElderlyCareMissionId = r.ElderlyCareMissionId,
                    CompletionTime = r.CompletionTime,
                    CompletionAtSpecifiedTime = r.CompletionAtSpecifiedTime,
                    CompletionBy = r.CompletionBy,
                    RecordContent = r.RecordContent,
                    ElderlyCareRecordMediaList = new List<ElderlyCareRecordMediaDto>(),
                    CareWorkerEmployeeNames = new List<string>(),
                };

                // 媒体内容
                if (!string.IsNullOrEmpty(r.ElderlyCareRecordMediaJson))
                {
                    line.ElderlyCareRecordMediaList = JsonConvert.DeserializeObject<List<ElderlyCareRecordMediaDto>>(r.ElderlyCareRecordMediaJson)!;
                }
                // 照护完成人名称
                if (employeeDic.ContainsKey(r.CompletionBy))
                {
                    line.CompletionByName = employeeDic[r.CompletionBy].Name;
                }
                // 照护项目执行护工列表
                if (!r.CareWorkerEmployeeIds.IsNullOrEmpty())
                {
                    var careWorkerEmployeeIds = r.CareWorkerEmployeeIds.Split(',');
                    foreach (var careWorkerEmployeeId in careWorkerEmployeeIds)
                    {
                        var careWorkerEmployeeIdLong = long.Parse(careWorkerEmployeeId);
                        if (employeeDic.ContainsKey(careWorkerEmployeeIdLong))
                        {
                            line.CareWorkerEmployeeNames.Add(employeeDic[careWorkerEmployeeIdLong].Name);
                        }
                    }
                }

                list.Add(line);
            }

            return Result<ElderlyCareRecordDto>.PageSuccess(list, total, input);
        }
    }
}